﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameManager : MonoBehaviour {
    //得分
    public int score = 0;
    //脚本实例
    public static GameManager Inst;
    void Awake()
    {
        Inst = this;
    }
	// Use this for initialization
	void Start () {
	
	}
    //重开游戏.todo
    void restart() 
    { 
        //todo.
    }
    //将要移动的cube列表
    List<NumCube> willmove=new List<NumCube>();
    /// <summary>
    /// 得到将要移动的列表
    /// </summary>
    /// <param name="p">方向</param>
    void getWillmoveCubeList(CubePos p)
    {
        List<NumCube> l=NumCube.cubes;
        if (p.x == 0)
        {
            //对y进行整理

            int y, k;
            if (p.y == -1)//向下,从0-3
            { y = 0; k = 4; }
            else//向上从4-0
            { y = 3; k = -1; }
            
            for (; p.y==-1?y < k:y>k; y+=p.y*-1)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    if (l[i].pos.y == y)
                    {
                        willmove.Add(l[i]);
                    }
                }
            }
        }
        else
        {

            //对x进行整理

            int x, k;
            if (p.x == -1)//向左 0-3
            { x = 0; k = 4; }
            else
            { x = 3; k = -1; }
            for (; p.x==-1?x < k:x>k; x+=p.x*-1)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    if (l[i].pos.x == x)
                    {
                        willmove.Add(l[i]);
                    }
                }
            }
        }
    }
    /// <summary>
    /// 移动
    /// </summary>
    /// <param name="p">方向</param>
    void move(CubePos p)
    {
        getWillmoveCubeList(p);
        foreach (NumCube c in willmove)
        {
            c.move(p);
        }
        if (NumCube.moved)//如果移动
        {
            Instantiate(willmove[0]);//生成
        }
        NumCube.moved = false;//重置开关
        willmove.Clear();//清空
    }
	// 这里有着输入控制
	void Update () {
        CubePos p = new CubePos();
        if (Input.GetKeyUp("up"))
        {
            p.x = 0; p.y = 1;
            move(p);
        }
        if (Input.GetKeyUp("down"))
        {
            p.x = 0; p.y = -1;
            move(p);
        }
        if (Input.GetKeyUp("left"))
        {
            p.x = -1; p.y = 0;
            move(p);
        }
        if (Input.GetKeyUp("right"))
        {
            p.x = 1; p.y = 0;
            move(p);
        }
        
	}
}
